package shopping.stateful;

import java.util.List;

import javax.ejb.EJBException;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import shopping.model.Shoppingcart;
import shopping.remote.IShoppingCartRemote;

@Stateful(name = "ShoppingCartStateful", mappedName = "ejb/ShoppingCartStateful")
public class ShoppingCartStateful implements IShoppingCartRemote {

	@PersistenceContext(unitName = "sem")
	EntityManager sem;

	@Override
	public void add(String userName, int productID) {
		try {
			Query query = sem.createNamedQuery("FindByAcc");
			query.setParameter(0, userName);
			query.setParameter(1, productID);
			List shoppingcarts = query.getResultList();
			if (shoppingcarts.isEmpty()) {
				sem.getTransaction().begin();
				Shoppingcart shoppingcart = new Shoppingcart();
				shoppingcart.setAccountID(userName);
				shoppingcart.setProductID(productID);
				shoppingcart.setQuantity(1);
				sem.persist(shoppingcart);
				sem.refresh(shoppingcart);
				sem.getTransaction().commit();
			} else {
				sem.getTransaction().begin();
				Shoppingcart shoppingcart = (Shoppingcart) shoppingcarts.get(0);
				shoppingcart.setQuantity(shoppingcart.getQuantity() + 1);
				sem.getTransaction().commit();
			}
		} catch (EJBException ex) {
			throw ex;
		}
	}

	@Override
	public void remove(String userName, int productID) {
		try {
			Query query = sem.createNamedQuery("FindByAcc");
			query.setParameter(0, userName);
			query.setParameter(1, productID);
			List shoppingcarts = query.getResultList();
			if (shoppingcarts.isEmpty()) {
				throw new EJBException("can't found this shoppingcart");
			} else {
				sem.getTransaction().begin();
				Shoppingcart shoppingcart = (Shoppingcart) shoppingcarts.get(0);
				sem.remove(shoppingcart);
				sem.getTransaction().commit();
			}
		} catch (EJBException ex) {
			throw ex;
		}
	}

	@Override
	public void alter(String userName, int productID, int number) {

	}

	@Override
	public List getAllCart(String userName) {
		return null;
	}

}
